package org.lhh.server.service.impl;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang3.StringUtils;
import org.lhh.server.common.api.JSONResult;
import org.lhh.server.common.utils.EhcacheUtil;
import org.lhh.server.common.utils.IDUtils;
import org.lhh.server.config.init.KeyPairInit;
import org.lhh.server.config.web.exception.BaseException;
import org.lhh.server.config.web.exception.UnAuthorizedException;
import org.lhh.server.core.repository.EtlRepository;
import org.lhh.server.service.IUserService;
import org.pentaho.di.repository.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.crypto.Cipher;
import java.nio.charset.StandardCharsets;

/**
 * @author 辉仔
 * @since 2019-05-28
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private EhcacheUtil ehcacheUtil;

    @Override
    public JSONResult authLogin(String username, String password) {
        if (StringUtils.isBlank(username)) {
            throw new BaseException("账号不能为空！");
        }
        if (StringUtils.isBlank(password)) {
            throw new BaseException("密码不能为空！");
        }
        UserInfo userInfo = EtlRepository.getUserInfo(username);
        if (userInfo == null) {
            throw new BaseException("用户不存在！");
        }

        try {
            byte[] cipherDataByte = Base64.decodeBase64(password.getBytes(StandardCharsets.UTF_8));
            Cipher cipher = Cipher.getInstance("RSA");
            cipher.init(Cipher.DECRYPT_MODE, KeyPairInit.keyPair.getPrivate());
            password = new String(cipher.doFinal(cipherDataByte));
        } catch (Exception e) {
            throw new BaseException("密码解密失效：请重新刷新", e);
        }

        if (!userInfo.getPassword().equals(password)) {
            throw new BaseException("密码错误！");
        }
        if (!userInfo.isEnabled()) {
            throw new BaseException("账号被锁定,请联系管理员！");
        }
        String token = IDUtils.getId();
        ehcacheUtil.putUser(token, userInfo);
        return JSONResult.ok(token);
    }


    @Override
    public boolean authUser(String token) {
        if (StringUtils.isEmpty(token)) {
            throw new UnAuthorizedException("登录认证已过期，请重新登录");
        }
        UserInfo loginUser = ehcacheUtil.getUser(token);
        if (loginUser == null) {
            throw new UnAuthorizedException("登录认证已过期，请重新登录");
        }
        UserInfo userInfo = EtlRepository.getUserInfo(loginUser.getLogin());
        if (userInfo == null) {
            throw new UnAuthorizedException("用户已被删除,请联系管理员！");
        }
        if (!userInfo.isEnabled()) {
            throw new UnAuthorizedException("账号已被锁定,请联系管理员！");
        }
        return true;
    }
}
